package com.jm.web.form;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.jsp.JspWriter;

import com.jm.utils.StringHelper;
import com.jm.utils.Utils;
import com.jm.web.form.support.FormItem;
import com.jm.web.tags.support.BaseTag;
import com.jm.web.tags.toolbar.ToolBarTag;
import com.jm.wf.data.WFOpStep;
import com.jm.wf.data.WFStep;

/**
 * @author yanjie
 *
 * 2011/9/19 上午11:27:53
 * 工具栏
 */
public class Toolbar extends FormItem{
	protected ToolBarTag tbTag = null;
	protected List defaultItems = null ;
	Button newButton = null; 
	Button searchButton = null;
	Button printButton = null;
	Button printPreviewButton = null;
	Button printStepButton = null;
	boolean bDisableAllButton = false;
	String strExceptButton = "";
	String strDisableButton = "";
	
	public void disableAllButton(){
		disableAllButtonExcept("");
	}
	
	public void disableButton(String strDisableButton){
		this.strDisableButton = strDisableButton;
	}
	
	public void disableAllButtonExcept(String strExceptButton){
		this.bDisableAllButton = true;
		this.strExceptButton = strExceptButton;
	}
	
	public Toolbar(){
	}
	
	/**
	 * @param tag
	 */
	public void InitTag(BaseTag tag) {
		super.InitTag(tag);
		this.tbTag = (ToolBarTag) tag;
		if(this.getBaseTag().getPage().isWFCheckPage()){
			LoadWFButtons();
		}else{
			LoadButtons();
		}
	}

	@Override
	public void init() {
		super.init();
		
		//处理自定义的工具栏按钮
		List customItems = this.getItems();
		if(customItems != null)
		{
			if(!this.getBaseTag().getPage().isWFCheckPage()){
				for (Iterator iter = customItems.iterator(); iter.hasNext();) {
					FormItem item = (FormItem) iter.next();
					if(item.getPos() > 0 && item.getPos() < defaultItems.size()){
						defaultItems.add(item.getPos(),item);
					}else{
						defaultItems.add(item);
					}
				}
			}
			this.getItems().clear();
			
			if(this.getBaseTag().getPage().isWFStartPage()){
				try {
					this.getBaseTag().getPage().getBaseAction().ProcessWFStartPageButton(this,defaultItems);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			this.getItems().addAll(defaultItems);
		}
	}
	
	@Override
	public void outItemBody(JspWriter writer) {
		try {
			for (Iterator iterator = this.items.iterator(); iterator.hasNext();) {
				Object object = iterator.next();
				if(object instanceof Separate){
					Separate sep = (Separate)object;
					
					writer.write("\r\n<td width=\"2px\">");
					sep.onRender(writer);
					writer.write("</td>");
				}else if(object instanceof Button){
					Button button = (Button)object;
					if(this.bDisableAllButton){
						if(StringHelper.IsNullOrEmpty(this.strExceptButton) 
								|| (","+this.strExceptButton+",").indexOf(","+button.getName()+",") < 0){
							button.setDisabled(true);
						}
					}
					
					if(!StringHelper.IsNullOrEmpty(this.strDisableButton) 
							&& (","+this.strDisableButton+",").indexOf(","+button.getName()+",") >= 0){
						button.setDisabled(true);
					}
					
					if(button.isEnab()){
						writer.write("\r\n<td class=\"toobar-td-cell\">");
						button.onRender(writer);
						writer.write("</td>");
					}
				}else if(object instanceof FormItem){
						FormItem item = (FormItem)object;
						writer.write("\r\n<td class=\"toobar-td-cell\">");
						item.onRender(writer);
						writer.write("</td>");
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	@Override
	public void outItemBegin(JspWriter writer) {
		
	}
	
	@Override
	public void outItemEnd(JspWriter writer) {
		
	}
	
	/**
	 * 加载默认的工具栏
	 * @throws Exception 
	 */
	protected void LoadWFButtons() {
		if(defaultItems == null)
			defaultItems = new ArrayList();
		else
			defaultItems.clear();
		
		if(this.getItems() != null)
			this.getItems().clear();
		
//		Utils utils = this.getBaseTag().getPage().getUtils();
		WFStep curWFStep = this.getBaseTag().getPage().getCurWFStep();
		WFOpStep curWFOpStep = this.getBaseTag().getPage().getCurWFOpStep();
		
		if(curWFStep == null || curWFOpStep == null || curWFOpStep.isFinsh()){
			Button closeBtn =  getNewButton("關閉頁面" ,"wfclosepage","wfclosepage","sx-tb-cancel",this.getBaseTag());
			closeBtn.setOnClick("top.close();");
			defaultItems.add(closeBtn);
			return;
		}
		String stepaction = curWFStep.getWFStepAction();//eg:1#OK-0#不OK
		Separate sep = new Separate();
		sep.InitTag(this.getBaseTag());
		for (int i = 0; i < stepaction.split("-").length; i++) {
			if(i > 0){
				defaultItems.add(sep);
			}
			String action = stepaction.split("-")[i];
			Button wfBtn =  getNewButton(action.split("#")[1] ,"wfcheck","wfcheck","sx-tb-commonaction",this.getBaseTag());
			wfBtn.setOnClick("var _P = {action:'wfcheck',actionvalue:'"+action+"',actiontext:'"+action.split("#")[1]+"'};if(params && params != undefined)$.extend(_P,params);return doAction(_P);");
			try {
				this.getBaseTag().getPage().getBaseAction().ProcessWFCheckPageButton(wfBtn);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			defaultItems.add(wfBtn);
		}
		Button closeBtn =  getNewButton("關閉頁面" ,"wfclosepage","wfclosepage","sx-tb-cancel",this.getBaseTag());
		closeBtn.setOnClick("top.close();");
		defaultItems.add(closeBtn);
		try {
			this.getBaseTag().getPage().getBaseAction().ProcessWFCheckPageButtons(defaultItems);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	/**
	 * 加载默认的工具栏
	 * @throws Exception 
	 */
	protected void LoadButtons() {
		if(defaultItems == null)
			defaultItems = new ArrayList();
		else
			defaultItems.clear();
		Utils utils = this.getBaseTag().getPage().getUtils();
		
		String args[] = {"","",""};
		newButton = getNewButton(utils.i18n(this.tbTag.GetExtValue("newText","新增")),"new","new",this.tbTag.GetExtValue("newIcon","sx-tb-new"),this.getBaseTag());
		newButton.setDisabled(this.tbTag.GetExtValue("newDisabled",this.getBaseTag().getPage().isBtnDisabled("new")));
		newButton.setEnab(this.tbTag.GetExtValue("newEnab",this.GetExtValue("newEnab",true)));
		newButton.setOnClick("var _P = {action:'"+this.tbTag.GetExtValue("newaction","new")+"',actionvalue:'"+this.tbTag.GetExtValue("newactionvalue","")+"',actiontext:'"+newButton.getValue()+"'};if(params && params != undefined)$.extend(_P,params);return doAction(_P);");
		newButton.setOption(this.tbTag.GetExtValue("newoption"));
		newButton.setMenuWidth(this.tbTag.GetExtValue("newMenuWidth",""));
		
		searchButton = getNewButton(utils.i18n(this.tbTag.GetExtValue("searchText","查詢")),"search","search",this.tbTag.GetExtValue("searchIcon","sx-tb-search"),this.getBaseTag());
		searchButton.setDisabled(this.tbTag.GetExtValue("searchDisabled",this.getBaseTag().getPage().isBtnDisabled("search")));
		searchButton.setEnab(this.tbTag.GetExtValue("searchEnab",this.GetExtValue("searchEnab",true)));
		searchButton.setOnClick("$('input[id=_page]').val('');var _P = {action:'"+this.tbTag.GetExtValue("searchaction","search")+"',actionvalue:'"+this.tbTag.GetExtValue("searchactionvalue","")+"',actiontext:'"+searchButton.getValue()+"'};if(params && params != undefined)$.extend(_P,params);return doAction(_P);");
		searchButton.setOption(this.tbTag.GetExtValue("searchoption"));
		searchButton.setMenuWidth(this.tbTag.GetExtValue("searchMenuWidth",""));
		
		Button saveButton = getNewButton(utils.i18n(this.tbTag.GetExtValue("saveText","儲存")),"save","save",this.tbTag.GetExtValue("saveIcon","sx-tb-save"),this.getBaseTag());
		saveButton.setDisabled(this.tbTag.GetExtValue("saveDisabled",this.getBaseTag().getPage().isBtnDisabled("save")));
		saveButton.setEnab(this.tbTag.GetExtValue("saveEnab",this.GetExtValue("saveEnab",true)));
		saveButton.setOnClick("var _P = {action:'"+this.tbTag.GetExtValue("saveaction","save")+"',actionvalue:'"+this.tbTag.GetExtValue("saveactionvalue","")+"',actiontext:'"+saveButton.getValue()+"'};if(params && params != undefined)$.extend(_P,params);return doAction(_P);");
		saveButton.setOption(this.tbTag.GetExtValue("saveoption"));
		saveButton.setMenuWidth(this.tbTag.GetExtValue("saveMenuWidth",""));
		
		Button cancelButton = getNewButton(utils.i18n(this.tbTag.GetExtValue("cancelText","取消")),"cancel","cancel",this.tbTag.GetExtValue("cancelIcon","sx-tb-cancel"),this.getBaseTag());
		cancelButton.setDisabled(this.tbTag.GetExtValue("cancelDisabled",this.getBaseTag().getPage().isBtnDisabled("cancel")));
		cancelButton.setEnab(this.tbTag.GetExtValue("cancelEnab",this.GetExtValue("cancelEnab",true)));
		cancelButton.setOnClick("var _P = {action:'"+this.tbTag.GetExtValue("cancelaction","cancel")+"',actionvalue:'"+this.tbTag.GetExtValue("cancelactionvalue","")+"',actiontext:'"+cancelButton.getValue()+"'};if(params && params != undefined)$.extend(_P,params);return doAction(_P);");
		cancelButton.setOption(this.tbTag.GetExtValue("canceloption"));
		cancelButton.setMenuWidth(this.tbTag.GetExtValue("cancelMenuWidth",""));
		
		Button deleteButton = getNewButton(utils.i18n(this.tbTag.GetExtValue("deleteText","刪除")),"delete","delete",this.tbTag.GetExtValue("deleteIcon","sx-tb-delete"),this.getBaseTag());
		deleteButton.setDisabled(this.tbTag.GetExtValue("deleteDisabled",this.getBaseTag().getPage().isBtnDisabled("delete")));
		deleteButton.setEnab(this.tbTag.GetExtValue("deleteEnab",this.GetExtValue("deleteEnab",true)));
		deleteButton.setOnClick("var _P = {action:'"+this.tbTag.GetExtValue("searchaction","delete")+"',actionvalue:'"+this.tbTag.GetExtValue("deleteactionvalue","")+"',actiontext:'"+deleteButton.getValue()+"'};if(params && params != undefined)$.extend(_P,params);return doAction(_P);");
		deleteButton.setOption(this.tbTag.GetExtValue("deleteoption"));
		deleteButton.setMenuWidth(this.tbTag.GetExtValue("deleteMenuWidth",""));
		
		Button copyButton = getNewButton(utils.i18n(this.tbTag.GetExtValue("copyText","複製")),"copy","copy",this.tbTag.GetExtValue("copyIcon","sx-tb-copy"),this.getBaseTag());
		copyButton.setDisabled(this.tbTag.GetExtValue("copyDisabled",this.getBaseTag().getPage().isBtnDisabled("copy")));
		copyButton.setEnab(this.tbTag.GetExtValue("copyEnab",this.GetExtValue("copyEnab",true)));
		copyButton.setOnClick("var _P = {action:'"+this.tbTag.GetExtValue("copyaction","copy")+"',actionvalue:'"+this.tbTag.GetExtValue("copyactionvalue","")+"',actiontext:'"+copyButton.getValue()+"'};if(params && params != undefined)$.extend(_P,params);return doAction(_P);");
		copyButton.setOption(this.tbTag.GetExtValue("copyoption"));
		copyButton.setMenuWidth(this.tbTag.GetExtValue("copyMenuWidth",""));
		
		Button startButton = getNewButton(utils.i18n(this.tbTag.GetExtValue("startText","送簽")),"start","start",this.tbTag.GetExtValue("startIcon","sx-tb-start"),this.getBaseTag());
		startButton.setDisabled(this.tbTag.GetExtValue("startDisabled",this.getBaseTag().getPage().isBtnDisabled("start")));
		startButton.setEnab(this.tbTag.GetExtValue("startEnab",this.GetExtValue("startEnab",true)));
		startButton.setOnClick("var _P = {action:'"+this.tbTag.GetExtValue("startaction","start")+"',actionvalue:'"+this.tbTag.GetExtValue("startactionvalue","")+"',actiontext:'"+startButton.getValue()+"'};if(params && params != undefined)$.extend(_P,params);return doAction(_P);");
		startButton.setOption(this.tbTag.GetExtValue("startoption"));
		startButton.setMenuWidth(this.tbTag.GetExtValue("startMenuWidth",""));
		
		Button checkButton = getNewButton(utils.i18n(this.tbTag.GetExtValue("checkText","審核")),"check","check",this.tbTag.GetExtValue("checkIcon","sx-tb-ok"),this.getBaseTag());
		checkButton.setDisabled(this.tbTag.GetExtValue("checkDisabled",this.getBaseTag().getPage().isBtnDisabled("check")));
		checkButton.setEnab(this.tbTag.GetExtValue("checkEnab",this.GetExtValue("checkEnab",true)));
		checkButton.setOnClick("var _P = {action:'"+this.tbTag.GetExtValue("checkaction","check")+"',actionvalue:'"+this.tbTag.GetExtValue("checkactionvalue","")+"',actiontext:'"+checkButton.getValue()+"'};if(params && params != undefined)$.extend(_P,params);return doAction(_P);");
		checkButton.setOption(this.tbTag.GetExtValue("checkoption"));
		checkButton.setMenuWidth(this.tbTag.GetExtValue("checkMenuWidth",""));
		
		Button exportButton = getNewButton(utils.i18n("導出"),"export","export","sx-tb-export",this.getBaseTag());
		exportButton.setDisabled(this.tbTag.GetExtValue("exportDisabled",this.getBaseTag().getPage().isBtnDisabled("export")));
		exportButton.setEnab(this.tbTag.GetExtValue("exportEnab",this.GetExtValue("exportEnab",true)));
		exportButton.setOnClick("var _P = {action:'"+this.tbTag.GetExtValue("exportaction","export")+"',actionvalue:'"+this.tbTag.GetExtValue("exportactionvalue","")+"',actiontext:'"+exportButton.getValue()+"'};if(params && params != undefined)$.extend(_P,params);return doAction(_P);");
		Object exportObject = this.tbTag.GetExtValue("exportoption");
		if(exportObject == null){
			exportObject = new LinkedHashMap();
			((Map)exportObject).put(utils.i18n("導出")+" Excel", StringHelper.Format("{id:'xls',value:'xls',confirm:'%1$s',disabled:'%2$s'}",this.tbTag.GetExtValue("xlsconfirm","false"),this.tbTag.GetExtValue("xlsdisabled","")));
		}
		exportButton.setOption(exportObject);
		exportButton.setMenuWidth(this.tbTag.GetExtValue("exportMenuWidth",""));
		
		
		if(this.getBaseTag().getPage().isSupportPrint()){//列印模式
			//列印
			printButton = getNewButton(utils.i18n("列印"),"print","print","sx-tb-print",this.getBaseTag());
			printButton.setDisabled(this.tbTag.GetExtValue("printDisabled",this.getBaseTag().getPage().isBtnDisabled("print")));
			printButton.setEnab(this.tbTag.GetExtValue("printEnab",this.GetExtValue("printEnab",true)));
			printButton.setOnClick("var _P = {action:'print',actionvalue:'',actiontext:'"+printButton.getValue()+"'};if(params && params != undefined)$.extend(_P,params);return doAction(_P);");
			
			//列印预览
			printPreviewButton = getNewButton(utils.i18n("列印预览"),"printPreview","printPreview","sx-tb-preview",this.getBaseTag());
			printPreviewButton.setDisabled(this.tbTag.GetExtValue("printPreviewDisabled",this.getBaseTag().getPage().isBtnDisabled("printPreviewDisabled")));
			printPreviewButton.setEnab(this.tbTag.GetExtValue("printPreviewEnab",this.GetExtValue("printPreviewEnab",true)));
			printPreviewButton.setOnClick("var _P = {action:'printpreview',actionvalue:'',actiontext:'"+printPreviewButton.getValue()+"'};if(params && params != undefined)$.extend(_P,params);return doAction(_P);");
			
			//列印设置
			printStepButton = getNewButton(utils.i18n("列印设置"),"printStep","printStep","sx-tb-commonaction",this.getBaseTag());
			printStepButton.setDisabled(this.tbTag.GetExtValue("printStepDisabled",this.getBaseTag().getPage().isBtnDisabled("printStepDisabled")));
			printStepButton.setEnab(this.tbTag.GetExtValue("printStepEnab",this.GetExtValue("printStepEnab",true)));
			printStepButton.setOnClick("var _P = {action:'printstep',actionvalue:'',actiontext:'"+printStepButton.getValue()+"'};if(params && params != undefined)$.extend(_P,params);return doAction(_P);");
			
		}else{
			printButton = getNewButton(utils.i18n("列印"),"print","print","sx-tb-print",this.getBaseTag());
			printButton.setDisabled(this.tbTag.GetExtValue("printDisabled",this.getBaseTag().getPage().isBtnDisabled("print")));
			printButton.setEnab(this.tbTag.GetExtValue("printEnab",this.GetExtValue("printEnab",true)));
			printButton.setOnClick("var _P = {action:'print',actionvalue:'',actiontext:'"+printButton.getValue()+"'};if(params && params != undefined)$.extend(_P,params);return doAction(_P);");
			printButton.setOption(this.tbTag.GetExtValue("printoption"));
			printButton.setMenuWidth(this.tbTag.GetExtValue("printMenuWidth",""));
		}
		
		
		Button helpButton = getNewButton(utils.i18n("幫助"),"help","help","sx-tb-help",this.getBaseTag());
		helpButton.setDisabled(this.tbTag.GetExtValue("helpDisabled",this.getBaseTag().getPage().isBtnDisabled("help")||StringHelper.IsNullOrEmpty(this.getBaseTag().getPage().getHelpURL())));
		helpButton.setEnab(this.tbTag.GetExtValue("helpEnab",this.GetExtValue("helpEnab",true)));
		helpButton.setOnClick("var _P = {action:'help',actionvalue:'',actiontext:'"+helpButton.getValue()+"'};if(params && params != undefined)$.extend(_P,params);return doAction(_P);");
		helpButton.setOption(this.tbTag.GetExtValue("helpoption"));
		helpButton.setMenuWidth(this.tbTag.GetExtValue("helpMenuWidth",""));
		
		Separate sep = new Separate();
		sep.InitTag(this.getBaseTag());
		
		defaultItems.add(newButton);
		defaultItems.add(searchButton);
		
		if(newButton.isEnab() || searchButton.isEnab())
			defaultItems.add(sep);
		
		defaultItems.add(saveButton);
		defaultItems.add(cancelButton);
		defaultItems.add(deleteButton);
		defaultItems.add(copyButton);
		
		if(saveButton.isEnab() || cancelButton.isEnab() || deleteButton.isEnab() || copyButton.isEnab())
			defaultItems.add(sep);
		
		defaultItems.add(startButton);
		defaultItems.add(checkButton);
		if(startButton.isEnab() || startButton.isEnab())
			defaultItems.add(sep);
		
		defaultItems.add(exportButton);
		defaultItems.add(printButton);
		if(this.getBaseTag().getPage().isSupportPrint()){//列印模式
			defaultItems.add(printPreviewButton);
			defaultItems.add(printStepButton);
			defaultItems.add(sep);
		}
		defaultItems.add(helpButton);
		
		
	}
	
	public static Button getNewButton(String strValue,String strId,String strName,String strIcon,BaseTag tag){
		Button btn = new Button();
		btn.InitTag(tag);
		btn.init();
		btn.appendCss("toobar-button");
		
		btn.setValue(strValue);
		btn.setId(strId);
		btn.setName(strName);
		btn.setIcon(strIcon);
		btn.SetExtValue("extInfo"," onmousedown=\"if($(this).isactive())$(this).addClass('ax-btn-pressed');\" onmouseup=\"if($(this).isactive())$(this).removeClass('ax-btn-pressed');\"  onmouseover=\"if($(this).isactive())$(this).addClass('ax-btn-over');\" onmouseout=\"if($(this).isactive())$(this).removeClass('ax-btn-over').removeClass('ax-btn-pressed');\" ");
		return btn;
	}
}
